#include "common.h"

void inputError()
{
        // error in input, exit
        printf("Input error\n");
        exit(1);
}
void mallocError()
{
        // error in allocating memory on cpu, exit
        printf("Malloc error\n");
        exit(1);
}
void cudaMallocError()
{
        // error in allocating memoryon gpu, exit
        printf("CUDA malloc error\n");
        exit(1);
}

//safely malloc
void* safe_malloc(size_t size)
{
    void* ptr = NULL;
    ptr = malloc(size);
    if (ptr == NULL)
        mallocError();

    return ptr;
}

//safely realloc
void* safe_realloc(void* ptr, size_t size)
{
    ptr = realloc(ptr, size);
    if (ptr == NULL)
        mallocError();

    return ptr;
}

//allocate memory on gpu
void* safe_cudaMalloc(size_t size)
{
    void* gpuPtr = NULL;
    
    if(cudaMalloc(&gpuPtr, size)== cudaErrorMemoryAllocation)
        cudaMallocError();

    return gpuPtr;
}

//allocate memory on cpu
void* safe_cudaMallocHost(size_t size)
{
    void* cpuPtr = NULL;
    
    if(cudaMallocHost(&cpuPtr, size)== cudaErrorMemoryAllocation)
        cudaMallocError();

    return cpuPtr;
}

unsigned int msb32(register unsigned int x)
{
	x |= (x >> 1);
	x |= (x >> 2);
	x |= (x >> 4);
	x |= (x >> 8);
	x |= (x >> 16);
	return(x & ~(x >> 1));
}


